<script lang="ts">
    import { onDestroy, onMount } from "svelte";
    import { tweened } from "svelte/motion";

    import { angle1 as angle1_rad, angle2 as angle2_rad, ani_speed } from '$lib/data';


    let canvas: HTMLCanvasElement | null = null;
    let ctx: CanvasRenderingContext2D | null = null;

    let motor_img = new Image();
    let arm_img = new Image();
    motor_img.src = "/Robot-user/电机.png"; 
    arm_img.src = "/Robot-user/上臂1.png"; 

    let base_w = $state(100);
    let base_h = $state(100);

    let motor1_x = $state(400);
    let motor1_y = $state(0);

    let arm1_x = $derived(motor1_x - (base_w/2));
    let arm1_y = $derived(motor1_y + (base_h - 15));

    let motor2_x = $derived(motor1_x);
    let motor2_y = $derived(arm1_y + base_h*2 - 10);

    let arm2_x = $derived(arm1_x);
    let arm2_y = $derived(motor2_y + base_h - 15);

    //把tweened视为数据会有精度和性能问题。
    const angle1 = tweened();
    const angle2 = tweened();

    angle1_rad.subscribe(v => {
        angle1.set(v, {duration: $ani_speed});
    });
    angle2_rad.subscribe(v => {
        angle2.set(v, {duration: $ani_speed});
    });

    onMount(() => {
        //这里是为了强制canvas刷新，因为有时dom切换canvas不会刷新
        $angle1 = Math.random()*100;
        $angle2 = Math.random()*100;
        onload()
        // $angle1 = 0;
        // $angle2 = 0;

        $angle1 = $angle1_rad;
        $angle2 = $angle2_rad;
    });

    onDestroy(() => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        if(ctx != null){
            ctx = null;
        };
        if(canvas != null){
            canvas = null;
        };
    });

    $effect(() => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.save();

        ctx.drawImage(motor_img, motor1_x, motor1_y, base_w, base_h);

        ctx.translate(motor1_x + base_w/2, motor1_y + base_h/2);
        ctx.rotate($angle1)
        //数值不会算都是猜的
        ctx.drawImage(arm_img, -base_w, base_w/2 - 15, base_w*2, base_h*2);
        ctx.drawImage(motor_img, -base_w/2, base_h*2 + 25, base_w, base_h);

        ctx.translate(-base_w/2 + base_w/2, base_h*2 + base_h - 25);
        ctx.rotate($angle2)

        ctx.drawImage(arm_img, -base_w, 35, base_w*2, base_h*2);
        
        ctx.restore();
    });

    function onload(){
        if (ctx == null || canvas == null){
            ctx = canvas.getContext('2d');
            ctx.imageSmoothingEnabled = true;
            ctx.imageSmoothingQuality = "high";
        }
        ctx.drawImage(motor_img, motor1_x, motor1_y, base_w, base_h);
        ctx.drawImage(arm_img, arm1_x, arm1_y, base_w*2, base_h*2);
        ctx.drawImage(motor_img, motor2_x, motor2_y, base_w, base_h);
        ctx.drawImage(arm_img, arm2_x, arm2_y, base_w*2, base_h*2);
    };
</script>

<canvas bind:this={canvas} width="500" height="580"></canvas>
